package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"starry_sky/internal/core"
	login_dto "starry_sky/internal/dto/login-dto"
	"starry_sky/internal/middleware/http-middleware"
	"starry_sky/internal/model"
	"starry_sky/internal/service"
	"starry_sky/internal/service/user-service"
	"starry_sky/internal/tools/encryption"
	"starry_sky/internal/tools/logger"
)

// AuthHandler 登录验证
func AuthHandler(c *gin.Context) {
	// 用户发送用户名和密码过来
	var user model.User
	if logger.HasError(c.ShouldBindJSON(&user)) {
		c.JSON(http.StatusInternalServerError, core.NewError(core.BAD_REQUEST, "请求参数不正确"))
		return
	}
	sysUser, err := user_service.FindUserByUserName(user.Username)
	// 校验用户名和密码是否正确
	if sysUser.ID == core.EmptyID {
		c.JSON(http.StatusInternalServerError, core.NewError(core.NO_SUCH_DATA, "用户不存在"))
		return
	}
	if encryption.MD5(user.Password) != sysUser.Password {
		c.JSON(http.StatusInternalServerError, core.NewError(core.FORBIDDEN, "用户不存在"))
		return
	}
	// 生成Token
	tokenString, refreshTokenString, err := http_middleware.GenToken(sysUser.ID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, core.NewError(core.INTERNAL_SERVER_ERROR, err.Error()))
		return
	}
	loginLog := model.LoginLog{
		UserId: sysUser.ID,
		Ip:     c.ClientIP(),
	}
	err = service.Insert(&loginLog)
	if err != nil {
		c.JSON(http.StatusInternalServerError, core.NewError(core.INTERNAL_SERVER_ERROR, err.Error()))
		return
	}
	// 更新用户登录时间和ip
	updateUserMap := make(map[string]any)
	updateUserMap["login_date"] = loginLog.CreatedAt
	updateUserMap["login_ip"] = c.ClientIP()
	err = service.UpdateForMap(&sysUser, updateUserMap)
	if err != nil {
		c.JSON(http.StatusInternalServerError, core.NewError(core.INTERNAL_SERVER_ERROR, err.Error()))
		return
	}
	returnMap := make(map[string]any)
	returnMap["nickname"] = sysUser.Nickname
	returnMap["token"] = tokenString
	returnMap["refreshToken"] = refreshTokenString
	c.JSON(http.StatusOK, core.OK.WithData(returnMap))
	return

}

func RefreshToken(c *gin.Context) {
	var refreshToken login_dto.RefreshToken
	if logger.HasError(c.ShouldBindJSON(&refreshToken)) {
		c.JSON(http.StatusInternalServerError, core.NewError(core.BAD_REQUEST, "请求参数不正确"))
		return
	}
	newToken, newRefreshToken, err := http_middleware.GenNewTokenFromRefreshToken(refreshToken.RefreshToken)
	if err != nil {
		c.JSON(http.StatusInternalServerError, core.NewError(core.INTERNAL_SERVER_ERROR, err.Error()))
		return
	}
	returnMap := make(map[string]any)
	returnMap["token"] = newToken
	returnMap["refreshToken"] = newRefreshToken
	c.JSON(http.StatusOK, core.OK.WithData(returnMap))
}
